//
//  NativeListDemoVC.m
//  JAGatherAdDemo
//
//  Created by Yc on 2024/7/11.
//

#import "NativeListDemoVC.h"
#import <JAGatherAdSDK/JAGatherAdSDK.h>
#import <MJRefresh/MJRefresh.h>
#import "NativeDemoCell.h"
#import "NativeModel.h"

@interface NativeListDemoVC ()<UITableViewDelegate,UITableViewDataSource,JAGAdNativeDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArrM;

@property (nonatomic, strong) NSMutableArray *nativeAdList;

@end

@implementation NativeListDemoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupTableView];
}

- (void)setupTableView {
    [self.view addSubview:self.tableView];
    __weak typeof(self) ws = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        __strong typeof(ws) self = ws;
        [self cleanData];
        [self loadNativeAd];
    }];

    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        __strong typeof(ws) self = ws;
        [self loadNativeAd];
    }];
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.tableView.frame = self.view.bounds;
}

- (void)loadNativeAd {
    
    JAGAdNative * nativeAd = [[JAGAdNative alloc] initWithPlacementID:self.placement adSize:CGSizeMake(self.tableView.bounds.size.width, self.tableView.bounds.size.width/16*9)];
    nativeAd.viewController = self;
    nativeAd.delegate = self;
    [nativeAd loadAd];
    [self.nativeAdList addObject:nativeAd];
    
}

- (void)showNativeAd:(NSArray *)feedAds {
    
    for (JAGNativeFeedAdModel *adModel in feedAds) {
        
        if (!adModel.isNativeExpress && ![adModel.adMaterialMeta isAdValid]) {
            continue;
        }
        NSLog(@"[AD]showNativeAd %@",adModel.adMaterialMeta);
        NativeModel *model = [[NativeModel alloc] init];
        model.adModel = adModel;
        __weak typeof(self) ws = self;
        [model setHandleCloseAction:^(JAGNativeFeedAdModel * _Nonnull adModel) {
            __strong typeof(ws) self = ws;
            [self deleteReloadData:adModel];
        }];
        [self.dataArrM addObjectsFromArray:[self loadDefaultData]];
        [self.dataArrM addObject:model];
    }
    [self.tableView reloadData];
}

- (NSArray *)loadDefaultData {
    NSMutableArray *array = [NSMutableArray new];
    for (int i = 0; i < 10; ++i) {
        NativeModel *model = [[NativeModel alloc] init];
        [array addObject:model];
    }
    return array.copy;
}

- (void)cleanData {
    [self.dataArrM removeAllObjects];
    [self.nativeAdList removeAllObjects];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource & UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArrM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NativeModel *model = self.dataArrM[indexPath.row];
    
    if (model.adModel) {
        
        NativeDemoCell *cell = (NativeDemoCell*)[tableView dequeueReusableCellWithIdentifier:@"JAGAdNativeExpress"];
        if (!cell) {
           cell = [[NativeDemoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"JAGAdNativeExpress"];
        }
        cell.model = self.dataArrM[indexPath.row];
        return cell;
        
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
        }
        cell.textLabel.text = [NSString stringWithFormat:@"标题 %ld",(long)indexPath.row];
        return cell;
    }

}

- (CGFloat)tableView:(UITableView *)tableView
  heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NativeModel *model = self.dataArrM[indexPath.row];
    return [model cellHeight];
 }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)deleteReloadData:(JAGNativeFeedAdModel *)feedAd {
    
    for (NativeModel *model in self.dataArrM) {
        if (model.adModel && model.adModel == feedAd) {
            [model.adView removeFromSuperview];
            model.adModel = nil;
            model.adView = nil;
            [self.dataArrM removeObject:model];
            break;
        }
    }
    [self.tableView reloadData];
}


#pragma mark - JAGAdNativeDelegate

/// 信息流广告加载成功
- (void)JAGatherNativedAdLoadSuccess:(JAGAdNative *)nativeAd feedAds:(NSArray <JAGNativeFeedAdModel *> *)feedAds {
    NSLog(@"%s", __FUNCTION__);
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    [self showNativeAd:feedAds];
}

/// 信息流广告加载失败
- (void)JAGatherNativeAdFailToLoad:(JAGAdNative *)nativeAd error:(NSError *)error {
    NSLog(@"%s %@", __FUNCTION__,error);
    [self.nativeAdList removeObject:nativeAd];
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

/// 信息流广告渲染成功
- (void)JAGatherNativeAdRenderSuccess:(JAGAdNative *)nativeAd feedAd:(JAGNativeFeedAdModel *)feedAd {
    NSLog(@"%s", __FUNCTION__);
    // 模版广告渲染成功 高度更新
    [self.tableView reloadData];
}

/// 信息流广告渲染失败
- (void)JAGatherNativeAdRenderFail:(JAGAdNative *)nativeAd feedAd:(JAGNativeFeedAdModel *)feedAd error:(NSError *)error {
    NSLog(@"%s", __FUNCTION__);
    [self deleteReloadData:feedAd];
    [self.nativeAdList removeObject:nativeAd];
}

/// 信息流广告曝光
- (void)JAGatherNativeAdDidExpourse:(JAGAdNative *)nativeAd feedAd:(JAGNativeFeedAdModel *)feedAd {
    NSLog(@"%s", __FUNCTION__);
}

/// 信息流广告点击
- (void)JAGatherNativeAdClicked:(JAGAdNative *)nativeAd feedAd:(JAGNativeFeedAdModel *)feedAd {
    NSLog(@"%s", __FUNCTION__);
}

/// 信息流广告关闭
- (void)JAGatherNativeAdClosed:(JAGAdNative *)nativeAd feedAd:(JAGNativeFeedAdModel *)feedAd {
    NSLog(@"%s", __FUNCTION__);
    [self deleteReloadData:feedAd];
    [self.nativeAdList removeObject:nativeAd];
}

/// 信息流广告关闭落地页
- (void)JAGatherNativeAdDidCloseLandingPage:(JAGAdNative *)nativeAd feedAd:(JAGNativeFeedAdModel *)feedAd {
    NSLog(@"%s", __FUNCTION__);
}

/// 信息流视频广告播放状态
- (void)JAGatherNativeAdVideoDidChanged:(JAGAdNative *)nativeAd playState:(JAGVideoPlayState)playState feedAd:(JAGNativeFeedAdModel *)feedAd {
    NSLog(@"%s playState : %zd", __FUNCTION__ , playState);
}



#pragma mark - Lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        [_tableView registerClass:[NativeDemoCell class] forCellReuseIdentifier:@"JAGAdNativeExpress"];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.allowsSelection = NO;
    }
    return _tableView;
}

- (NSMutableArray *)dataArrM {
    if (!_dataArrM) {
        _dataArrM = [[NSMutableArray alloc] init];
    }
    return _dataArrM;
}

- (NSMutableArray *)nativeAdList {
    if (!_nativeAdList) {
        _nativeAdList = [[NSMutableArray alloc] init];
    }
    return _nativeAdList;
}

- (void)dealloc {
    NSLog(@"%s", __FUNCTION__);
}

@end
